using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Collections;
using System.Xml.Serialization;
using System.Reflection;
using System.Globalization;

namespace uk.org.aspellclark.todolistppc
{
    /// <summary>
    ///   <name>Preferences</name>
    ///   <namespace>Arcsoft.AthleteLog</namespace>
    ///   <version>1.0</version>
    ///   <author>Andy Aspell-Clark</author>
    ///   <description>This class holds preferences for the application
    ///   </description>
    ///   <history>
    ///     <historyitem> 6 Aug 2004  1.0 ARA  Initial Version.</historyitem>
    ///   </history>
    /// </summary>
    [ XmlRoot("preferences") ]
	public class PreferencesXml
	{
        [XmlElement("Filename")]
		private string m_sFileName = "todolistppc.xml";

        [ XmlElement("FileCreation") ]
        private DateTime m_dtFileCreationTime;

        [ XmlElement("Preferences") ]
        private Hashtable m_htPrefs;

        /// <summary>
        /// 
        /// </summary>
		public PreferencesXml()
		{
			m_htPrefs = new Hashtable();

            Assembly asm = Assembly.GetExecutingAssembly();
            CultureInfo ci = asm.GetName().CultureInfo;

            m_sFileName = asm.GetName().ToString();
            int indexOf = m_sFileName.IndexOf(",");
            m_sFileName = m_sFileName.Substring(0, indexOf);
            m_sFileName += "-prefs.xml";

			DirectoryInfo dir = new DirectoryInfo(".");
			foreach (FileInfo f in dir.GetFiles(m_sFileName)) 
			{
				m_sFileName          = f.FullName;
				m_dtFileCreationTime = f.CreationTime;
				break;
			}

			readFromFile();
		}


        /// <summary>
        /// 
        /// </summary>
        /// <param name="psName"></param>
        /// <returns></returns>
		public string getPreference(string psName)
		{
			if (m_htPrefs.ContainsKey(psName))
			{
				return (string)m_htPrefs[psName];
			}
			else
			{
				return "";
			}
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="psName"></param>
        /// <param name="psValue"></param>
        /// <returns></returns>
        public void setPreference(string psName, string psValue)
        {
            if (m_htPrefs.ContainsKey(psName))
            {
                m_htPrefs[psName] = psValue;
            }
            else
            {
                m_htPrefs.Add(psName, psValue);
            }
        }

        /// <summary>
        /// 
        /// </summary>
		public void readFromFile()
		{
			XmlTextReader reader = null;
			try
			{
				// Load the file with an XmlTextReader
				//Console.WriteLine ("Reading file {0} ...", CommonFunctions.GetApplicationPath() + System.IO.Path.DirectorySeparatorChar + m_sFileName);
				reader = new XmlTextReader (CommonFunctions.ApplicationPath + System.IO.Path.DirectorySeparatorChar + m_sFileName);
				//Console.WriteLine ("File {0} read sucessfully ...", CommonFunctions.GetApplicationPath() + System.IO.Path.DirectorySeparatorChar + m_sFileName);

				// Process the supplied XML file
				//Console.WriteLine ("Processing ...");
				//Console.WriteLine ();
				FormatXml(reader, m_sFileName);
			}
			catch (Exception e)
			{
                string sMsg = e.Message;
				//Console.WriteLine ("Failed to read the file {0}", m_sFileName);
				//Console.WriteLine ("Exception: {0}", e.ToString());
			}
			finally
			{
				//Console.WriteLine();
				//Console.WriteLine("Processing of the file {0} complete.", m_sFileName);
				// Finished with XmlTextReader
				if (reader != null)
				{
					reader.Close();
				}
			}//finally
		}

		private void FormatXml (XmlReader reader, String filename)
		{
			int declarationCount = 0;
			int piCount = 0;
			int docCount = 0;
			int commentCount = 0;
			int elementCount = 0;
			int attributeCount = 0;
			int textCount = 0;
			int whitespaceCount = 0;

			while (reader.Read())
			{
				switch (reader.NodeType)
				{
					case XmlNodeType.XmlDeclaration:
						Format (reader, "XmlDeclaration");
						declarationCount++;
						break;
					case XmlNodeType.ProcessingInstruction:
						Format (reader, "ProcessingInstruction");
						piCount++;
						break;
					case XmlNodeType.DocumentType:
						Format (reader, "DocumentType");
						docCount++;
						break;
					case XmlNodeType.Comment:
						Format (reader, "Comment");
						commentCount++;
						break;
					case XmlNodeType.Element:
						Format (reader, "Element");
						elementCount++;
						string sName = "";
						string sValue = "";
						if (reader.Name == "Item")
						{
							if (reader.HasAttributes)
							{
								attributeCount += reader.AttributeCount;        
								while (reader.MoveToNextAttribute())
								{
									if (reader.Name == "Name") 
									{
										sName = reader.Value;
									}
									else if (reader.Name == "Value") 
									{
										sValue = reader.Value;
									}
								}
							}
							m_htPrefs.Add(sName, sValue);
						}
						break;
					case XmlNodeType.Text:
						Format (reader, "Text");
						textCount++;
						break;
					case XmlNodeType.Whitespace:
						whitespaceCount++;
						break;
				}
			}

			// Display the Statistics for the file.
//			Console.WriteLine ();
//			Console.WriteLine("Statistics for {0} file", filename);
//			Console.WriteLine ();
//			Console.WriteLine("XmlDeclaration: {0}",declarationCount++);
//			Console.WriteLine("ProcessingInstruction: {0}",piCount++);
//			Console.WriteLine("DocumentType: {0}",docCount++);
//			Console.WriteLine("Comment: {0}",commentCount++);
//			Console.WriteLine("Element: {0}",elementCount++);
//			Console.WriteLine("Attribute: {0}",attributeCount++);
//			Console.WriteLine("Text: {0}",textCount++);
//			Console.WriteLine("Whitespace: {0}",whitespaceCount++);
		}

		private void Format(XmlReader reader, String nodeType)
		{
			// Format the output
//			Console.Write(reader.Depth + " ");
//			Console.Write(reader.AttributeCount + " ");
			for (int i = 0; i < reader.Depth; i++)
			{
				//Console.Write('\t');
			}

			//Console.Write(reader.Prefix + nodeType + "<" + reader.Name + ">" + reader.Value);

			// Display the attributes values for the current node
			if (reader.HasAttributes)
			{
				//Console.Write(" Attributes:");

				for (int j = 0; j < reader.AttributeCount; j++)
				{
					//Console.Write(" [{0}] " + reader[j], j);
				}
			}
			//Console.WriteLine();
		}

        /// <summary>
        /// 
        /// </summary>
		public void writeToFile()
        {
//            if (File.Exists(CommonFunctions.GetApplicationPath() + System.IO.Path.DirectorySeparatorChar + m_sFileName))
//            {
//                if (File.Exists(CommonFunctions.GetApplicationPath() + System.IO.Path.DirectorySeparatorChar + m_sFileName + ".bak"))
//                {
//                    File.Delete(CommonFunctions.GetApplicationPath() + System.IO.Path.DirectorySeparatorChar + m_sFileName + ".bak");
//                }
//                File.Move(CommonFunctions.GetApplicationPath() + System.IO.Path.DirectorySeparatorChar + m_sFileName, CommonFunctions.GetApplicationPath() + System.IO.Path.DirectorySeparatorChar + m_sFileName + ".bak");
//            }
            XmlTextWriter xmlWriter = new XmlTextWriter(CommonFunctions.ApplicationPath + System.IO.Path.DirectorySeparatorChar + m_sFileName, System.Text.Encoding.UTF8);
            xmlWriter.WriteStartDocument();

            //write out the root element - Project
            xmlWriter.WriteStartElement("Preferences");

            xmlWriter.WriteAttributeString("", "FILENAME", "", m_sFileName);

            foreach (string str in m_htPrefs.Keys)
            {
                xmlWriter.WriteStartElement("Item");

                xmlWriter.WriteAttributeString("", "Name", "", str);
                xmlWriter.WriteAttributeString("", "Value", "", m_htPrefs[str].ToString());

                xmlWriter.WriteEndElement();
            }

            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndDocument();
            xmlWriter.Flush();
            xmlWriter.Close();
		}

	}//class()
}//namespace()
